var dns = require('native-dns');
var _ = require('underscore');

function calcDuration(times){

  return {
    duration: times.end - times.start
  };
}

var _ns_server = '114.114.114.114';

function detect(options, callback){
  var times = {};

  var question = dns.Question({
    name: options.name,
    type: options.type || 'A'
  });

  var dnsServer = [];

  times.start = Date.now();

  var req = dns.Request({
    question: question,
    server: options.ns || _ns_server ,
    timeout: options.timeout || 3000,
  });  

  var ip = [];

  req.on('timeout', function () {
    times.timeout = Date.now();
  });

  req.on('message', function (err, answer) {
    answer.answer.forEach(function (a) {
      ip.push(a.address);
    });
  });  

  req.on('end', function () {
    times.end = Date.now();
    callback({
      timeout: !!times.timeout,
      times: times,
      result:{
        ip: ip
      }
    });
  });

  req.on('cancelled ',function(){
    times.cancelled = Date.now();
  });

  req.send();  

}




exports.detect = detect;




